///  author : douyu
///  date : 2023/12/20 13:52
///  description :

import 'dart:io';

import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_android_tv/Routes/Model/source_info_model.dart';
import 'package:flutter_android_tv/Routes/Event/event_bus_type.dart';
import 'package:flutter_android_tv/Routes/Tools/keyboard_code.dart';
import 'package:flutter_android_tv/Routes/Notifier/source_change_notifier.dart';
import 'package:flutter_android_tv/common_tool/zjLogFile.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:provider/provider.dart';
import 'package:flutter_android_tv/common_tool/system_platform_tool.dart';
import '../part_refresh_widget/single_data_line.dart';
import 'package:flutter_android_tv/Routes/left_slider_menu.dart';
import 'package:flutter_android_tv/Routes/Tools/custom_dialog.dart';

class ZJHomeTVPage extends StatefulWidget {
  const ZJHomeTVPage({super.key});

  @override
  State<ZJHomeTVPage> createState() => _ZJHomeTVPageState();
}

class _ZJHomeTVPageState extends State<ZJHomeTVPage> with  SingleTickerProviderStateMixin, MultDataLine {
  final FijkPlayer player = FijkPlayer();
  /// player focus
  final FocusNode _playerNode = FocusNode();
  /// 当前正在播放的数据流
  late SourceInfoModel currentSource;

  late bool isTV = false;

  @override
  void initState() {
    super.initState();
    player.setOption(FijkOption.playerCategory, "framedrop", 5);
    player.setOption(FijkOption.formatCategory, "analyzeduration", 1);
    //设置重新加载视图
    player.addListener(_fijkValuePlayerListener);

    _updateLayout();
    /// 监听数据源变化
    eventBus.on<ChangePlaySourceEvent>().listen((event) {
      FlutterNativeSplash.remove();/// 移除启动图
      zjLog("上下切换888888===============${event.iptvSourceModel.name}");
      _startPlaySource(event.iptvSourceModel,sourceIndex: event.playIndex);
    });

    /// 退出app
    eventBus.on<ShowQuitDialogEvent>().listen((event) {
      showQuitAppDialog(context);
    });
  }

  void _updateLayout() {
    if(Platform.isAndroid){
      SystemPlatformChannel.checkTVDevice().then((value) async {
        //更新UI布局
        isTV = value;
        if(isTV){
          //更新对应样式,判断当前播放器状态
          if(player.state != FijkState.idle && player.state != FijkState.error){
            //重新播放当前数据
            String playerSource = currentSource.sources.first;
            await player.reset();
            player.setDataSource(playerSource,autoPlay: true);
          }
          setState(() {    });
        }
      });
    }
  }

  /// 播放器状态变换监听
  void _fijkValuePlayerListener() {
    //视图加载状态变化
    FijkState state = player.state;
    switch (state) {
      case FijkState.idle:
      case FijkState.initialized:
      case FijkState.asyncPreparing:
          EasyLoading.show(status: "玩命加载${currentSource.name}中……\n 上下键可切换频道");
        break;
      case FijkState.prepared:
      case FijkState.started:
        EasyLoading.dismiss();
        break;
      case FijkState.paused:
      case FijkState.completed:
      case FijkState.stopped:
      case FijkState.end:
        EasyLoading.dismiss();
        break;
      case FijkState.error:
        EasyLoading.showError("播放${currentSource.name}出错，正在尝试其他播放源请稍等……");
        break;
    }
  }

  /// 按钮点击事件监听
  void _onKeyBoardListener(RawKeyEvent eventKey) {
    if(eventKey.runtimeType.toString() == 'RawKeyDownEvent'){
      /// 点击事件 只有按键松开处理  长按不处理
      RawKeyEventDataAndroid data = eventKey.data as RawKeyEventDataAndroid;
      Provider.of<IPTVCategoryProvider>(context,listen: false).keyBoardPressListener(data.keyCode);
    }
  }

  void _startPlaySource(SourceInfoModel playSource, {int sourceIndex = 0}) async {
    /// 同一个播放源不重新拉取视频信息
    String liveSourceStr = playSource.sources[sourceIndex];
    if(liveSourceStr == player.dataSource){
      return;
    }
    currentSource = playSource;
    zjLog("上下切换999999=================${currentSource.name}");
    await player.reset();
    player.setDataSource(liveSourceStr,autoPlay: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      /// 监听遥控器点击事件
      body: RawKeyboardListener(
        focusNode: _playerNode,
        onKey: _onKeyBoardListener,
        child: isTV ? _showTVLayout() : _showPhoneLayout(),
      ),
    );
  }

  Widget _showPhoneLayout(){
    return Column(
      children: [
        FijkView(
            player: player,
            fit: FijkFit.fill,
            height: 250,
        ),
        ZJLeftSlideMenu(
          isTV:isTV,
          pressCallback: (int selectIndex) {
            /// 模拟按键点击的操作
            Provider.of<IPTVCategoryProvider>(context,listen: false).keyBoardPressListener(KeyBoardCode.KEYCODE_DPAD_CENTER);
          },
        )
      ],
    );
  }


  Widget _showTVLayout(){
    return Stack(
      children: [
        FijkView(
            player: player,
            fit: FijkFit.fill,
            width: double.infinity,
            color: Colors.transparent,
            panelBuilder: fijkPanel2Builder()
        ),
        ZJLeftSlideMenu(
          isTV:isTV,
          pressCallback: (int selectIndex) {
            /// 模拟按键点击的操作
            Provider.of<IPTVCategoryProvider>(context,listen: false).keyBoardPressListener(KeyBoardCode.KEYCODE_DPAD_CENTER);
          },
        )
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    player.removeListener(_fijkValuePlayerListener);
    player.release();
    dataLineDispose();//释放资源
  }
}
